package com.doge.service.wx.order;

import com.doge.bean.base.BaseData;
import com.doge.bean.base.BaseParam;
import com.doge.bean.bo.order.CommentBO;
import com.doge.bean.bo.order.OrderSubmitBO;
import com.doge.bean.pojo.address.Address;
import com.doge.bean.pojo.aftersale.AfterSale;
import com.doge.bean.pojo.cart.Cart;
import com.doge.bean.pojo.cart.CartExample;
import com.doge.bean.pojo.comment.Comment;
import com.doge.bean.pojo.coupon.Coupon;
import com.doge.bean.pojo.coupon.CouponExample;
import com.doge.bean.pojo.coupon.CouponUser;
import com.doge.bean.pojo.coupon.CouponUserExample;
import com.doge.bean.pojo.order.Order;
import com.doge.bean.pojo.order.OrderExample;
import com.doge.bean.pojo.order.OrderGoods;
import com.doge.bean.pojo.order.OrderGoodsExample;
import com.doge.bean.vo.order.*;
import com.doge.mapper.*;
import com.doge.util.auth.GetSubject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: OrderServiceImpl
 * @Description:
 * @author: PuJing
 * @create: 2021-12-02-14:14
 **/
@Service
public class WxOrderServiceImpl implements WxOrderService {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderGoodsMapper orderGoodsMapper;
    @Autowired
    CartMapper cartMapper;
    @Autowired
    AddressMapper addressMapper;
    @Autowired
    CouponMapper couponMapper;
    @Autowired
    SystemMapper systemMapper;
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    CouponUserMapper couponUserMapper;
    @Autowired
    AfterSaleMapper afterSaleMapper;


    @Override
    public BaseData list(BaseParam baseParam, Integer showType) {

        PageHelper.startPage(baseParam.getPage(), baseParam.getLimit());

        OrderExample orderExample = new OrderExample();

        OrderExample.Criteria criteria = orderExample.createCriteria();

        // 判断一下showType代表的订单状态  showType=0 全部
        // 0 全部
        // 1 待付款  101 未付款
        // 2 待发货  201 已付款
        // 3 待收货  301 已发货
        // 4 待评价  401 402 用户收货、系统收货
        if (showType == 0) {

            List<Short> shortList = new ArrayList<>();
            shortList.add((short) 101);
            shortList.add((short) 102);
            shortList.add((short) 103);
            shortList.add((short) 201);
            shortList.add((short) 202);
            shortList.add((short) 203);
            shortList.add((short) 301);
            shortList.add((short) 401);
            shortList.add((short) 402);
            criteria.andOrderStatusIn(shortList);

        } else if (showType == 1) {

            criteria.andOrderStatusEqualTo((short) 101);

        } else if (showType == 2) {

            criteria.andOrderStatusEqualTo((short) 201);
        } else if (showType == 3) {

            criteria.andOrderStatusEqualTo((short) 301);
        } else if (showType == 4) {

            List<Short> shortList2 = new ArrayList<>();
            shortList2.add((short) 401);
            shortList2.add((short) 402);
            criteria.andOrderStatusIn(shortList2);
        }

        // 逻辑删除，不能查询deleted为1的订单
        criteria.andDeletedEqualTo(false);

        orderExample.setOrderByClause("add_time" + " " + "desc");
        // 查询订单信息
        List<Order> orders = orderMapper.selectByExample(orderExample);

        // 封装到OrderListVO
        List<OrderListVO> orderListVOS = new ArrayList<>();


        for (Order order : orders) {

            OrderListVO orderListVO = new OrderListVO();

            orderListVO.setGroupin(false);

            // 新建HandleOptionVO
            HandleOptionVO handleOptionVO = new HandleOptionVO();

            // 查询订单的商品信息
            OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
            orderGoodsExample.createCriteria().andOrderIdEqualTo(order.getId());
            List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);

            // 封装到OrderListVO的goodsList
            orderListVO.setGoodsList(orderGoods);


            orderListVO.setAftersaleStatus(order.getAftersaleStatus());
            orderListVO.setOrderSn(order.getOrderSn());
            orderListVO.setActualPrice(order.getActualPrice());
            orderListVO.setId(order.getId());

            if (order.getOrderStatus() == 101) {
                orderListVO.setOrderStatusText("未付款");

                // 封装到OrderListVO的handleOption
                handleOptionVO.setCancel(true);
                handleOptionVO.setPay(true);

            } else if (order.getOrderStatus() == 102) {
                orderListVO.setOrderStatusText("已取消");
                handleOptionVO.setDelete(true);

            } else if (order.getOrderStatus() == 103) {
                orderListVO.setOrderStatusText("已取消(系统)");
                handleOptionVO.setDelete(true);

            } else if (order.getOrderStatus() == 201) {
                orderListVO.setOrderStatusText("已付款");
                handleOptionVO.setRefund(true);

            } else if (order.getOrderStatus() == 202) {
                orderListVO.setOrderStatusText("申请退款");

            } else if (order.getOrderStatus() == 203) {
                orderListVO.setOrderStatusText("已退款");

            } else if (order.getOrderStatus() == 301) {
                orderListVO.setOrderStatusText("已发货");
                handleOptionVO.setConfirm(true);

            } else if (order.getOrderStatus() == 401) {
                orderListVO.setOrderStatusText("已收货");
                handleOptionVO.setDelete(true);
                handleOptionVO.setComment(true);
                handleOptionVO.setRebuy(true);
                handleOptionVO.setAftersale(true);

            } else if (order.getOrderStatus() == 402) {
                orderListVO.setOrderStatusText("已收货(系统)");
                handleOptionVO.setDelete(true);
                handleOptionVO.setComment(true);
                handleOptionVO.setRebuy(true);
                handleOptionVO.setAftersale(true);
            }

            // 封装到OrderListVO的handleOption
            orderListVO.setHandleOption(handleOptionVO);

            orderListVOS.add(orderListVO);
        }

        PageInfo info = new PageInfo(orders);

        long total = info.getTotal();
        Integer pages = info.getPages();
        Integer limit = info.getPageSize();
        Integer page = info.getPageNum();


        return new BaseData(page, limit, total, pages, orderListVOS);
    }


    @Override
    public OrderSubmitVO submit(OrderSubmitBO orderSubmitBO) {

        Order order = new Order();

        // 获得当前日期时间的String
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String yyyyMMdd = simpleDateFormat.format(date);

        int rs = (int) ((Math.random() * 9 + 1) * Math.pow(10, 5));
        String s = String.valueOf(rs);
        String concat = yyyyMMdd.concat(s);

        // 设置订单编号
        order.setOrderSn(concat);
        // 设置订单状态，都是未付款101
        order.setOrderStatus((short) 101);
        // 设置售后状态0
        order.setAftersaleStatus((short) 0);
        // 设置订单备注
        order.setMessage(orderSubmitBO.getMessage());

        // 根据addressId查询地址表
        Address address = addressMapper.getAddressByAddressId(orderSubmitBO.getAddressId());

        // 封装与address相关内容
        // 设置电话
        order.setMobile(address.getTel());
        // 设置收货人
        order.setConsignee(address.getName());

        String province = address.getProvince();
        String city = address.getCity();
        String county = address.getCounty();
        String allAddress = province.concat(city).concat(county);
        // 设置地址
        order.setAddress(allAddress);

        // 设置userId
        order.setUserId(GetSubject.getUserId());

        // 如果cartId 为0，表示submit当前用户所有已经check的cart
        List<Cart> carts = new ArrayList<>();
        if (orderSubmitBO.getCartId()==0) {
            // 根据userId和check查询购物车表，还要排除deleted为1的
            CartExample cartExample = new CartExample();
            cartExample.createCriteria().andUserIdEqualTo(GetSubject.getUserId()).andCheckedEqualTo(true).andDeletedEqualTo(false);
            carts = cartMapper.selectByExample(cartExample);
        }else {
            // 直接购买则通过 cartid 下单
            Cart cart = cartMapper.selectByPrimaryKey(orderSubmitBO.getCartId());
            carts.add(cart);
        }
        BigDecimal goodsPrice = new BigDecimal(0);

        for (Cart cart1 : carts) {
            goodsPrice = goodsPrice.add(cart1.getPrice().multiply(new BigDecimal(cart1.getNumber())));

        }
        // 设置订单商品总费用
        order.setGoodsPrice(goodsPrice);


        // 根据couponId查询优惠券表
        Coupon coupon = couponMapper.selectByPrimaryKey(orderSubmitBO.getCouponId());
                //getCouponByCouponId(orderSubmitBO.getCouponId());

        BigDecimal couponZero = new BigDecimal(0);
        if (coupon != null) {

            // TODO 比较  优惠券的使用金额限定 与 订单商品总费用

            // 使用了优惠券，设置优惠券减免
            order.setCouponPrice(coupon.getDiscount());

        } else {
            // 没有使用优惠券，设置优惠券减免为0
            order.setCouponPrice(couponZero);
        }


        // 查询满减价格，以及运费价格
        Integer market_express_freight_min = Integer.valueOf(systemMapper.getMarketSystemByKeyName("market_express_freight_min"));
        Integer market_express_freight_value = Integer.valueOf(systemMapper.getMarketSystemByKeyName("market_express_freight_value"));

        if (order.getGoodsPrice().intValue() >= market_express_freight_min) {
            // 设置运费价格
            order.setFreightPrice(new BigDecimal(0));
        } else {
            // 设置运费价格
            order.setFreightPrice(new BigDecimal(market_express_freight_value));
        }

        // 算出订单价格
        order.setOrderPrice(goodsPrice.add(order.getFreightPrice()).subtract(order.getCouponPrice()));
        // 设置实付费用
        order.setActualPrice(order.getOrderPrice());
        // 设置订单创建时间
        order.setAddTime(new Date());

        // 几个没有用到的值要设为0
        order.setIntegralPrice(new BigDecimal(0));
        order.setGrouponPrice(new BigDecimal(0));
        order.setPayId("0");
        order.setPayTime(new Date());

        // 向数据库中插入新订单信息
        int row = orderMapper.insertSelective(order);

        // 修改couponUser表
        if (coupon != null) {
            // 使用了优惠券
            // 把coupon-user里的优惠券状态status改为1,要用example，UserCouponId和UserId查询
            CouponUserExample couponUserExample = new CouponUserExample();
            couponUserExample.createCriteria().andCouponIdEqualTo(orderSubmitBO.getUserCouponId()).andUserIdEqualTo(GetSubject.getUser().getId());
            List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);
            // 找出该用户 该类型的 所有的优惠券

            for (CouponUser couponUser : couponUsers) {
                // 遍历

                if (couponUser.getOrderId()== null){
                    // 选择出没有使用的一张，然后更改状态，即使用掉

                    couponUser.setStatus((short) 1);
                    couponUser.setUsedTime(new Date());
                    couponUser.setOrderId(order.getId());
                    couponUser.setUpdateTime(new Date());

                    couponUserMapper.updateByPrimaryKeySelective(couponUser);

                    break;
                }

            }
            //CouponUser couponUser = couponUserMapper.selectByPrimaryKey(orderSubmitBO.getUserCouponId());
        }


        for (Cart cart1 : carts) {

            // 添加数据到OrderGoods表
            OrderGoods orderGoods = new OrderGoods();

            orderGoods.setOrderId(order.getId());
            orderGoods.setGoodsId(cart1.getGoodsId());
            orderGoods.setGoodsName(cart1.getGoodsName());
            orderGoods.setGoodsSn(cart1.getGoodsSn());
            orderGoods.setProductId(cart1.getProductId());
            orderGoods.setNumber((short) ((int) cart1.getNumber()));
            orderGoods.setPrice(cart1.getPrice());
            orderGoods.setSpecifications(cart1.getSpecifications());
            orderGoods.setPicUrl(cart1.getPicUrl());

            orderGoods.setComment(0);
            orderGoods.setAddTime(new Date());

            orderGoodsMapper.insertSelective(orderGoods);
        }

        // 修改购物车所有信息的deleted状态
        for (Cart cart2 : carts) {

            cart2.setUpdateTime(new Date());
            cart2.setDeleted(true);

            cartMapper.updateByPrimaryKey(cart2);
        }

        if (row == 1) {

            OrderSubmitVO orderSubmitVO = new OrderSubmitVO(order.getId(), 0);

            return orderSubmitVO;

        } else return null;
    }


    @Override
    public OrderForDetailVO detail(Integer orderId) {


        Order order = orderMapper.selectByPrimaryKey(orderId);

        // 封装到orderForDetailVO
        OrderForDetailVO orderForDetailVO = new OrderForDetailVO();

        // 封装到orderInfo
        OrderInfoForDetailVO orderInfoForDetailVO = new OrderInfoForDetailVO();

        orderInfoForDetailVO.setConsignee(order.getConsignee());
        orderInfoForDetailVO.setAddress(order.getAddress());
        orderInfoForDetailVO.setAddTime(order.getAddTime());
        orderInfoForDetailVO.setOrderSn(order.getOrderSn());
        orderInfoForDetailVO.setActualPrice(order.getActualPrice());
        orderInfoForDetailVO.setMobile(order.getMobile());
        orderInfoForDetailVO.setMessage(order.getMessage());
        orderInfoForDetailVO.setAftersaleStatus(order.getAftersaleStatus());
        orderInfoForDetailVO.setGoodsPrice(order.getGoodsPrice());
        orderInfoForDetailVO.setCouponPrice(order.getCouponPrice());
        orderInfoForDetailVO.setId(order.getId());
        orderInfoForDetailVO.setFreightPrice(order.getFreightPrice());

        // 新建HandleOptionVO
        HandleOptionVO handleOptionVO = new HandleOptionVO();

        if (order.getOrderStatus() == 101) {
            orderInfoForDetailVO.setOrderStatusText("未付款");

            // 封装到OrderListVO的handleOption
            handleOptionVO.setCancel(true);
            handleOptionVO.setPay(true);

        } else if (order.getOrderStatus() == 102) {
            orderInfoForDetailVO.setOrderStatusText("已取消");
            handleOptionVO.setDelete(true);

        } else if (order.getOrderStatus() == 103) {
            orderInfoForDetailVO.setOrderStatusText("已取消(系统)");
            handleOptionVO.setDelete(true);

        } else if (order.getOrderStatus() == 201) {
            orderInfoForDetailVO.setOrderStatusText("已付款");
            handleOptionVO.setRefund(true);

        } else if (order.getOrderStatus() == 202) {
            orderInfoForDetailVO.setOrderStatusText("申请退款");

        } else if (order.getOrderStatus() == 203) {
            orderInfoForDetailVO.setOrderStatusText("已退款");

        } else if (order.getOrderStatus() == 301) {
            orderInfoForDetailVO.setOrderStatusText("已发货");
            handleOptionVO.setConfirm(true);

        } else if (order.getOrderStatus() == 401) {
            orderInfoForDetailVO.setOrderStatusText("已收货");
            handleOptionVO.setDelete(true);
            handleOptionVO.setComment(true);
            handleOptionVO.setRebuy(true);
            handleOptionVO.setAftersale(true);

        } else if (order.getOrderStatus() == 402) {
            orderInfoForDetailVO.setOrderStatusText("已收货(系统)");
            handleOptionVO.setDelete(true);
            handleOptionVO.setComment(true);
            handleOptionVO.setRebuy(true);
            handleOptionVO.setAftersale(true);
        }

        orderInfoForDetailVO.setHandleOption(handleOptionVO);


        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        orderGoodsExample.createCriteria().andOrderIdEqualTo(orderId);

        List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);

        orderForDetailVO.setOrderInfo(orderInfoForDetailVO);
        orderForDetailVO.setOrderGoods(orderGoods);

        return orderForDetailVO;
    }

    @Override
    public int orderChangeStatus(Integer orderId, int orderStatus) {

        Order order = orderMapper.selectByPrimaryKey(orderId);

        order.setOrderStatus((short) orderStatus);
        order.setUpdateTime(new Date());

        int row = orderMapper.updateByPrimaryKey(order);

        if (row == 1) {
            return 200;
        } else return 404;

    }


    @Override
    public int delete(Integer orderId) {

        Order order = orderMapper.selectByPrimaryKey(orderId);


        order.setDeleted(true);
        order.setUpdateTime(new Date());

        int row = orderMapper.updateByPrimaryKey(order);

        if (row == 1) {
            return 200;
        } else return 404;
    }


    @Override
    public OrderGoods goods(Integer orderId, Integer goodsId) {

        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();

        orderGoodsExample.createCriteria().andOrderIdEqualTo(orderId).andGoodsIdEqualTo(goodsId);

        List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);

        return orderGoods.get(0);
    }


    @Override
    public int comment(CommentBO commentBO) {

        // 封装到comment
        Comment comment = new Comment();

        comment.setType((byte) 0);
        comment.setContent(commentBO.getContent());
        comment.setUserId(GetSubject.getUserId());

        comment.setPicUrls(commentBO.getPicUrls());

        if (commentBO.getPicUrls() == null) {

            comment.setHasPicture(false);
        } else {
            comment.setHasPicture(true);
        }

        comment.setStar(commentBO.getStar());
        comment.setAddTime(new Date());
        comment.setUpdateTime(new Date());


        OrderGoods orderGoods = orderGoodsMapper.selectByPrimaryKey(commentBO.getOrderGoodsId());

        comment.setValueId(orderGoods.getGoodsId());

        int row = commentMapper.insertSelective(comment);

        if (row == 1) {


            orderGoods.setComment(comment.getId());
            orderGoods.setUpdateTime(new Date());

            orderGoodsMapper.updateByPrimaryKeySelective(orderGoods);

            return 200;
        } else return 404;
    }

    @Override
    public int orderChangeConfirmStatus(Integer orderId, int orderStatus) {

        Order order = orderMapper.selectByPrimaryKey(orderId);

        order.setOrderStatus((short) orderStatus);
        order.setUpdateTime(new Date());
        order.setConfirmTime(new Date());

        int row = orderMapper.updateByPrimaryKey(order);

        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        orderGoodsExample.createCriteria().andOrderIdEqualTo(orderId);
        List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);

        for (OrderGoods orderGood : orderGoods) {

            orderGood.setUpdateTime(new Date());

            orderGoodsMapper.updateByPrimaryKey(orderGood);
        }

        if (row == 1) {
            return 200;
        } else return 404;

    }


    @Override
    public int orderRefund(Integer orderId, int orderStatus) {


        Order order = orderMapper.selectByPrimaryKey(orderId);

        order.setOrderStatus((short) orderStatus);
        order.setUpdateTime(new Date());
        // 还要更改order的售后状态aftersaleStatus
        order.setAftersaleStatus((short)1);


        int row = orderMapper.updateByPrimaryKey(order);


        // 向售后表中插入数据
        AfterSale afterSale = new AfterSale();

        // 获得当前日期时间的String
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String yyyyMMdd = simpleDateFormat.format(date);

        int rs = (int) ((Math.random() * 9 + 1) * Math.pow(10, 5));
        String s = String.valueOf(rs);
        String concat = yyyyMMdd.concat(s);

        afterSale.setAftersaleSn(concat);
        afterSale.setOrderId(order.getId());
        afterSale.setUserId(order.getUserId());
        afterSale.setType((short)0);
        //afterSale.setReason(order.getId());
        afterSale.setAmount(order.getActualPrice());
        //afterSale.setPictures(order.getId());
        //afterSale.setComment(order.getId());
        afterSale.setStatus((short)1);
        afterSale.setAddTime(new Date());
        afterSale.setHandleTime(new Date());
        afterSale.setUpdateTime(new Date());

        afterSaleMapper.insertSelective(afterSale);

        if (row == 1) {
            return 200;
        } else return 404;

    }



}
